package com.dtw.ditouwang.ui.movement;

import android.app.AlertDialog;
import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.PolylineOptions;
import com.bumptech.glide.Glide;
import com.dtw.ditouwang.R;
import com.dtw.ditouwang.beans.MovementBackBean;
import com.dtw.ditouwang.databinding.ActivityMovementOverBinding;
import com.dtw.ditouwang.models.WebApi;
import com.dtw.ditouwang.ui.BaseActivity;
import com.dtw.ditouwang.utils.ShareUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatMoments;

public class MovementOverActivity extends BaseActivity implements View.OnClickListener {
    public final static String KeyMoovementOverData = "KeyMoovementOverData";
    ActivityMovementOverBinding activityMovementOverBinding;
    MovementBackBean.DataBean movementBackBaen;
    LineChart lineChart;
    MapView mapView;
    TextView textView;
    ViewGroup tili, out;
    Bitmap mBitmap;
    ScrollView scrollView;
    ShareParams shareParams;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMovementOverBinding = DataBindingUtil.setContentView(this, R.layout.activity_movement_over);
        enableBack();
        setSubTitle(R.drawable.icon_share, this);
        lineChart = findViewById(R.id.linechart);
        mapView = findViewById(R.id.mapview);
        textView = findViewById(R.id.text_avg_max);
        tili = findViewById(R.id.view_tili);
        scrollView = findViewById(R.id.scrollview);
        out = findViewById(R.id.view_out);
        movementBackBaen = getIntent().getParcelableExtra(KeyMoovementOverData);
        movementBackBaen.setSpeed_distribution(String.format("%.0f′%02d″ ", (Float.parseFloat(movementBackBaen.getSpeed_distribution())) / 60, ((int) Float.parseFloat(movementBackBaen.getSpeed_distribution())) % 60));
        if ("0".equals(movementBackBaen.getTili())) {
            tili.setVisibility(View.GONE);
        }
        if (!"室外".equals(movementBackBaen.getRoom_type())) {
            out.setVisibility(View.GONE);
        }
        if ("走".equals(movementBackBaen.getType())) {
            movementBackBaen.setType("健走");
        } else if ("跑".equals(movementBackBaen.getType())) {
            movementBackBaen.setType("跑步");
        }

        activityMovementOverBinding.setMovement(movementBackBaen);
        setTitle(movementBackBaen.getRoom_type() + movementBackBaen.getType());
        mapView.onCreate(savedInstanceState);
        if ("2".equals(movementBackBaen.getRoom_type_id())) {
            //室外运动加载地图
            mapView.setVisibility(View.VISIBLE);
            AMap aMap = mapView.getMap();
//            aMap.setMaxZoomLevel(12);
            aMap.addPolyline(new PolylineOptions().addAll(movementBackBaen.getTrajectory())
                    .width(10).color(Color.argb(255, 1, 1, 1)));
            if (movementBackBaen.getTrajectory() != null) {
//                LatLngBounds latLngBounds = new LatLngBounds(movementBackBaen.getTrajectory().get(0), movementBackBaen.getTrajectory().get(movementBackBaen.getTrajectory().size() - 1));
//                aMap.setMapStatusLimits(latLngBounds);
                CameraUpdate mCameraUpdate;
                if(movementBackBaen.getTrajectory().size()<2){
                    mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(movementBackBaen.getTrajectory().get(0),18,0,0));
                }else{
                    mCameraUpdate=CameraUpdateFactory.newCameraPosition(new CameraPosition(
                            new LatLng((movementBackBaen.getTrajectory().get(0).latitude+movementBackBaen.getTrajectory().get(movementBackBaen.getTrajectory().size()-1).latitude)/2,
                                    (movementBackBaen.getTrajectory().get(0).longitude+movementBackBaen.getTrajectory().get(movementBackBaen.getTrajectory().size()-1).longitude)/2),18,0,0));
                }
                aMap.moveCamera(mCameraUpdate);
            }
        }
        initChart(movementBackBaen.getSubsection());
        initOutHourData(movementBackBaen.getSubsection());
        initView();
        if (movementBackBaen.getMedal() != null && movementBackBaen.getMedal().size() > 0) {
            for (MovementBackBean.DataBean.MedalBean medalBean : movementBackBaen.getMedal()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View dialog = LayoutInflater.from(this).inflate(R.layout.dialog_medal, null);
                builder.setView(dialog);
                builder.setPositiveButton("确定", null);
                builder.show();
                ImageView imageView = dialog.findViewById(R.id.imageview);
                TextView textView = dialog.findViewById(R.id.text_name);
                Glide.with(imageView).load(WebApi.BaseUrl + medalBean.getHighlight_img().replace("\\", "/")).into(imageView);
                textView.setText(medalBean.getMedal_name());
            }
        }
        scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                 mBitmap = Bitmap.createBitmap(scrollView.getMeasuredWidth(), scrollView.getChildAt(0).getMeasuredHeight(), Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(mBitmap);
                canvas.drawColor(Color.WHITE);//不设置底部会出现黑色
                scrollView.draw(canvas);
                shareParams = new ShareParams();
                shareParams.setShareType(Platform.SHARE_IMAGE);
                shareParams.setImageData(mBitmap);
            }
        });
    }

    float avgMax = 0, avg = 0;

    public void initChart(MovementBackBean.DataBean.SubsectionBean subsectionBean) {
        if (subsectionBean == null) {
            return;
        }
        ArrayList<Entry> entries = new ArrayList<>();
        for (int i = 0; i < subsectionBean.getValues().size(); i++) {
            Entry entrie = new Entry(i, subsectionBean.getValues().get(i).getValue());
            entries.add(entrie);
            if (subsectionBean.getValues().get(i).getValue() > avgMax) {
                avgMax = subsectionBean.getValues().get(i).getValue();
            }
            avg += subsectionBean.getValues().get(i).getValue();
        }
        if (subsectionBean.getValues().size() != 1) {
            avg = avg / subsectionBean.getValues().size();
        }
        textView.setText(String.format("最快速度 %.2f  平均速度 %.2f", avgMax, avg));
        if (entries.isEmpty()) {
            return;
        }
        LineDataSet lineDataSet = new LineDataSet(entries, "");
        lineDataSet.setValues(entries);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawFilled(true);
        lineDataSet.setLineWidth(1);
        lineDataSet.setDrawValues(false);
        lineDataSet.setDrawHighlightIndicators(false);
        lineDataSet.setColor(ContextCompat.getColor(this, R.color.commen_green));
        lineDataSet.setFillDrawable(ContextCompat.getDrawable(this, R.drawable.linechart_file));
        lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int) value + "";
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
        LineData data = new LineData(lineDataSet);
        lineChart.getDescription().setEnabled(false);
        lineChart.setData(data);
        lineChart.getAxisLeft().setDrawGridLines(false);
        lineChart.getAxisLeft().setAxisMinimum(0);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getXAxis().setDrawGridLines(false);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        lineChart.invalidate();
    }

    int mintus = 0;
    float hAvg;
    List<Float> hourAvg = new ArrayList<>();

    private void initOutHourData(MovementBackBean.DataBean.SubsectionBean subsectionBean) {
        if (subsectionBean == null) {
            return;
        }
        for (int i = 0; i < subsectionBean.getValues().size(); i++) {
            mintus++;
            hAvg += subsectionBean.getValues().get(i).getValue();
            if (mintus == 60) {
                hAvg = hAvg / 60;
                hourAvg.add(hAvg);
                hAvg = 0;
                mintus = 0;
            }
        }
        if (mintus > 0) {
            hAvg = hAvg / mintus;
            hourAvg.add(hAvg);
        }
        for (int i = 0; i < hourAvg.size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_movement_end, null);
            ((TextView) view.findViewById(R.id.text_position)).setText(i + "");
            TextView avgText = (view.findViewById(R.id.text_avg));
            avgText.setText(String.format("%.0f′%02.0f″", hourAvg.get(i), hourAvg.get(i) % 1 * 100));
            out.addView(view);
            avgText.getLayoutParams().width = avgText.getLayoutParams().width + ((int) (avgText.getWidth() + (hourAvg.get(i) - 1) * 20));
            avgText.requestLayout();
        }
    }

    Dialog dialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_sub_title:
                ShareUtil.share(this,shareParams);
                break;
        }
    }

    private void initView() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
